package br.com.rafsoft.mapaentrega.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import br.com.rafsoft.mapaentrega.MapaEntregaApplication;
import br.com.rafsoft.mapaentrega.R;
import br.com.rafsoft.mapaentrega.activity.async.AsyncFetchTask;
import br.com.rafsoft.mapaentrega.adapter.TaskAdapter;
import br.com.rafsoft.mapaentrega.shared.TaskProxy;

public class TaskListActivity extends Activity implements OnItemClickListener {
	
	private TaskAdapter adapter;
    private AsyncFetchTask task;
    private ListView listView;
    private ProgressBar progressBar;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_list);
        
        listView = (ListView) findViewById(R.id.listViewTask);
        progressBar = (ProgressBar) findViewById(R.id.progressBarTask);
        	
		MapaEntregaApplication mapaEntregaApplication = (MapaEntregaApplication) getApplication();
		adapter = mapaEntregaApplication.getTaskAdapter(this);
		listView.setAdapter(adapter);	
		listView.setOnItemClickListener(this);
		
		fetchTasks(-1);
		
    }

	public void addTasks(List<TaskProxy> tasks) {
		progressBar.setVisibility(View.GONE);
		adapter.addTasks(tasks);
		adapter.notifyDataSetChanged();
		//((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
	}

	public void setTasks(List<TaskProxy> tasks) {
		progressBar.setVisibility(View.GONE);
		adapter.setTasks(tasks);
		adapter.notifyDataSetChanged();
	}
	
	public void fetchTasks(long id) {
		progressBar.setVisibility(View.VISIBLE);
        if (task != null) {
            task.cancel(true);
        }
        task = new AsyncFetchTask(this);
        task.execute(id);
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent(this, TaskViewActivity.class);
        intent.putExtra("position", position);
        startActivityForResult(intent, 0);		
	}
	
	@Override
	protected void onActivityResult(int code, int result, Intent intent) {
		if (result == RESULT_OK) {
			setResult(RESULT_OK);
			finish();
		}
	}
	

}
